<template>
  <div class="iconfont-select">
    <el-select v-model="text" clearable filterable placeholder="请选择" @change="change">
      <el-option
        v-for="item in iconList"
        :key="item.icon_id"
        :label="item.name"
        :value="prefix+item.font_class">
        <div class="icon-option">
          <i class="iconfont" :class="prefix+item.font_class" style="font-size: 20px" v-if="!svg"></i>
          <svg v-else class="icon icon-select" aria-hidden="true">
            <use :xlink:href="prefix+item.font_class"></use>
          </svg>
          <span class="icon-value">{{item.name}}</span>
        </div>
      </el-option>
    </el-select>
    <div v-if="text" class="icon-preview" @click="previewIcon">
      <i class="iconfont icon" :class="text" style="font-size: 18px" v-if="!svg"></i>
      <svg v-else class="icon icon-select" aria-hidden="true">
        <use :xlink:href="text"></use>
      </svg>
    </div>
    <el-dialog
      title="图标预览"
      :visible.sync="previewIconVisible"
      append-to-body
      center
      width="30%">
      <div style="text-align: center">
        <i class="iconfont" :class="text" style="font-size: 200px" v-if="!svg"></i>
        <svg v-else class="icon icon-select" aria-hidden="true">
          <use :xlink:href="text"></use>
        </svg>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import iconData from '../../assets/iconfont/iconfont.json'
export default {
  name: 'iconfont-select',
  props: {
    value: String,
    svg: Boolean,
    prefix: {
      type: String,
      default: 'icon-'
    }
  },
  data () {
    return {
      previewIconVisible: false,
      iconList: iconData.glyphs || [],
      text: this.value
    }
  },
  methods: {
    change (value) {
      this.$emit('input', value)
      this.$emit('change', value)
    },
    previewIcon () {
      this.previewIconVisible = true
    }
  },
  watch: {
    value: {
      handler (n, o) {
        this.text = n
      },
      immediate: true
    }
  }
}
</script>

<style scoped lang="scss">
  .iconfont-select{
    display: flex;
  }
  .icon-preview{
    display: flex;
    padding: 0 10px;
    background-color: $--background-color-base;
    border-radius: 0 4px 4px 0;

    .icon{
      margin:auto;
    }
  }
  .icon-option{
    padding: 0 20px;
  }
  .icon-select {
    width: 20px;
    height: 20px;
    vertical-align: middle;
    transition: all .2s;
  &:hover {
     transform: scale(3);
   }
  }

  .icon-value {
    margin-left: 20px;
    vertical-align: middle;
  }

</style>

<style lang="scss">
  .iconfont-select{
    .el-input__inner{
      border-radius: 4px 0 0 4px ;
    }
  }
</style>
